package com.itsu.filter;

import com.itsu.domain.Module;
import com.sun.org.apache.xpath.internal.operations.Mod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.List;

@WebFilter(value = {"/store/*", "/system/*"})
public class UserPermissionFilter implements Filter {

    private FilterConfig filterConfig;

    /**
     * 初始化方法，获取过滤器的配置对象
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.定义和协议相关的请求和响应对象
        HttpServletRequest request ;
        HttpServletResponse response;
        List<String> moduleCUrls = null;
        try{
            //2.把参数转换成协议相关的对象
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)resp;
            String uri = request.getRequestURI();
            String queryString = request.getQueryString();
            String url = uri.substring(1);
            String[] split = queryString.split("&");
            url += "?" +split[0];
            System.out.println(url);

            if (url.endsWith("operation=login") || url.endsWith("operation=home")) {
                chain.doFilter(request,response);
                return;
            }

            moduleCUrls = (List<String>) request.getSession().getAttribute("moduleCUrl");
            if (moduleCUrls != null && moduleCUrls.size() > 0) {
                if (moduleCUrls.contains(url)) {
                    chain.doFilter(request,response);
                    return;
                }
            }

            response.sendRedirect("/unauthorized.jsp");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        //可以做一些清理操作
    }
}
